<?php
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Auth.php';
require_once 'Zend/Auth/Adapter/DbTable.php';
require_once 'Zend/Session/Namespace.php';
require_once 'application/models/User.php';

class UserController extends Zend_Controller_Action
{
    public function indexAction ()
    {
        $request = $this->getRequest();
        $auth = Zend_Auth::getInstance();
        if (! $auth->hasIdentity()) {
            $this->_redirect('/user/loginform');
        } else {
            $this->_redirect('/index/indexhome');
        }
    }
    
	public function processAction()
	{	
		// If the form has been submitted, process it
		if ($this->getRequest()->isPost()) {
			
			// Valid email address?
			if (! Zend_Validate::is($this->_request->getPost('email'), 'EmailAddress')) {
				(array)$this->view->errorsDes[] = "Invalid e-mail address.";
			} // end valid email
			
			// E-mail cannot already exist in database
			$user = new User();
			$foundUser = $user->getUserByEmail($this->_request->getPost('email'));
			$this->view->errorsDes = array();
			if ($foundUser != "") {
				$this->view->errorsDes[] = "E-mail address already in database.";
			}
			
			// Handle must be between 2 and 20 characters
			$validHandle = new Zend_Validate_StringLength(2,20);
			if (! $validHandle->isValid($this->_request->getPost('user_name'))) {
				(array)$this->view->errorsDes[] = "Handle must be between 2 and 14 characters.";
			} // end valid handle
			
			// Handle must consist solely of alphanumeric characters
			$validHandle = new Zend_Validate_Alnum();
			if (! $validHandle->isValid($this->_request->getPost('user_name'))) {
				(array)$this->view->errorsDes[] = "Handle must consist of letters and numbers.";
			} // end valid handle
			
			// Handle cannot already exist in database
			$foundUser = $user->getUserByHandle($this->_request->getPost('user_name'));
			if ($foundUser != "") {
				$this->view->errorsDes[] = "Handle already exists in database.";
			}
			
			// Password must be at least 6 characters
			$validPswd = new Zend_Validate_StringLength(6,20);
			if (! $validPswd->isValid($this->_request->getPost('password'))) {
				(array)$this->view->errorsDes[] = "Password must be at least 6 characters.";
			} // end valid password
			
			// First name must not be empty
			$validFirstName = new Zend_Validate_NotEmpty();
			if (! $validFirstName->isValid($this->_request->getPost('first_name'))) {
				(array)$this->view->errorsDes[] = "Please provide your first name.";
			} // end valid first name
			
			// Last name must not be empty
			$validLastName = new Zend_Validate_NotEmpty();
			if (! $validLastName->isValid($this->_request->getPost('last_name'))) {
				(array)$this->view->errorsDes[] = "Please provide your last name.";
			} // end valid last name
			
			// Valid gender?
			if (! Zend_Validate::is($this->_request->getPost('gender'), 'NotEmpty')) {
				(array)$this->view->errorsDes[] = "Please identify your gender.";
			} // end valid gender
			
			// If errors exist, prepare the form data for inclusion in the form so
			// the user doesn't have to repopulate the data
			if (count($this->view->errorsDes) > 0) {
			
				$this->view->email = $this->_request->getPost('email');
				$this->view->user_name = $this->_request->getPost('user_name');
				$this->view->first_name = $this->_request->getPost('first_name');
				$this->view->last_name = $this->_request->getPost('last_name');
				$this->view->gender = $this->_request->getPost('gender');
				$this->view->assign('action', "process");
		        $this->view->assign('title', 'Member Registration');
		        $this->view->assign('label_fname', 'First Name');
		        $this->view->assign('label_lname', 'Last Name');
		        $this->view->assign('label_uname', 'User Name');
		        $this->view->assign('label_pass', 'Password');
		        $this->view->assign('label_submit', 'Register');
		        $this->view->assign('description', 'Please enter this form completely:');
				$this->render('register');
			// No errors, add the user to the database and send the confirmation e-mail
			} else {
			
				// Generate the random key used for registration confirmation
				$registrationKey = $this->generate_random_string();
				
				// Prepare the data array for database insertion
				$data = array (
					'email' => $this->_request->getPost('email'),
					'password' => md5($this->_request->getPost('password')),
					'registration_key' => $registrationKey,
					'user_name' => $this->_request->getPost('user_name'),
					'first_name' => $this->_request->getPost('first_name'),
					'last_name' => $this->_request->getPost('last_name'),
					'gender' => $this->_request->getPost('gender'),
					'created_at' => date('Y-m-d H:i:s'),
					'updated_at' => date('Y-m-d H:i:s'),
					'last_login' => date('Y-m-d H:i:s')
				);
				
				// Insert the registration data into the database
				$user = new User();
				$user->insert($data);
			    
			}
		
		}
	}
    
    public function userpageAction ()
    {
        $auth = Zend_Auth::getInstance();
        if (! $auth->hasIdentity()) {
            $this->_redirect('/user/loginform');
        }
        $request = $this->getRequest();
        
        //Session control----------------------------------------
        $ns = new Zend_Session_Namespace('HelloWorld');
        if (! isset($ns->yourUserPageRequest)) {
            $ns->yourUserPageRequest = 1;
        } else {
            $ns->yourUserPageRequest ++;
        }
        $ns->setExpirationSeconds(60, 'yourUserPageRequest');
        $this->view->assign('request', $ns->yourUserPageRequest);
        
        //----------------------------------------
        $user = $auth->getIdentity();
        $real_name = $user->first_name;
        $username = $user->user_name;
        
        $logoutUrl = $request->getBaseURL() . '/user/logout';
        $editUrl = $request->getBaseURL() . '/user/edit';
        $listUrl = $request->getBaseURL() . '/user/list';
        
        $this->view->assign('username', $username);
        $this->view->assign('real_name', $real_name);
        $this->view->assign('urllogout', $logoutUrl);
        $this->view->assign('urllist', $listUrl);
        $this->view->assign('urledit', $editUrl);
        //$this->_redirect('/index/index');
    }
    public function logoutAction ()
    {
        $auth = Zend_Auth::getInstance();
        if (! $auth->hasIdentity()) {
            $this->_redirect('/user/loginform');
        }
        $auth->clearIdentity();
        $this->_redirect('/user');
    }
    public function loginformAction ()
    {
        $request = $this->getRequest();
        $ns = new Zend_Session_Namespace('HelloWorld');
        if (! isset($ns->yourLoginRequest)) {
            $ns->yourLoginRequest = 1;
        } else {
            $ns->yourLoginRequest ++;
        }
        $this->view->assign('request', $ns->yourLoginRequest);
        $request = $this->getRequest();
        $this->view->assign('action', $request->getBaseURL() . "/user/auth");
        $this->view->assign('title', 'Login Form');
        $this->view->assign('user_name', 'User Name');
        $this->view->assign('password', 'Password');
        $registerUrl = $request->getBaseURL() . '/user/register';
        $this->view->assign('urlregister', $registerUrl);
    }
    public function authAction ()
    {
        $request = $this->getRequest();
        $registry = Zend_Registry::getInstance();
        $auth = Zend_Auth::getInstance();
        $DB = $registry['DB'];
        $authAdapter = new Zend_Auth_Adapter_DbTable($DB);
        $authAdapter->setTableName('user')
            ->setIdentityColumn('user_name')
            ->setCredentialColumn('password');
        // Set the input credential values
        $uname = $request->getParam('username');
        $paswd = $request->getParam('password');
        $authAdapter->setIdentity($uname);
        $authAdapter->setCredential(md5($paswd));
        
        // Perform the authentication query, saving the result
        $result = $auth->authenticate($authAdapter);
        //print_r($result);
        if ($result->isValid()) {
            $data = $authAdapter->getResultRowObject(null, 'password');
            $auth->getStorage()->write($data);
            $this->_redirect('/user');
        } else {
            $errorMessage = "Wrong username or password provided. Please try again.";
            $this->_redirect('/user/loginform');
        }
    }
    public function nameAction ()
    {
        $request = $this->getRequest();
        $this->view->assign('name', $request->getParam('user_name'));
        $this->view->assign('gender', $request->getParam('gender'));
        $this->view->assign('title', 'User Name');
    }
    public function registerAction ()
    {
        $request = $this->getRequest();
        $this->view->assign('action', "process");
        $this->view->assign('title', 'Member Registration');
        $this->view->assign('label_fname', 'First Name');
        $this->view->assign('label_lname', 'Last Name');
        $this->view->assign('label_uname', 'User Name');
        $this->view->assign('label_pass', 'Password');
        $this->view->assign('label_submit', 'Register');
        $this->view->assign('description', 'Please enter this form completely:');
    }
    public function editAction ()
    {
        $registry = Zend_Registry::getInstance();
        $DB = $registry['DB'];
        $request = $this->getRequest();
        $id = $request->getParam("id");
        $sql = "SELECT * FROM `user` WHERE id='" . $id . "'";
        $result = $DB->fetchRow($sql);
        $this->view->assign('data', $result);
        $this->view->assign('action', 
        $request->getBaseURL() . "/user/processedit");
        $this->view->assign('title', 'Member Editing');
        $this->view->assign('label_fname', 'First Name');
        $this->view->assign('label_lname', 'Last Name');
        $this->view->assign('label_uname', 'User Name');
        $this->view->assign('label_pass', 'Password');
        $this->view->assign('label_submit', 'Edit');
        $this->view->assign('description', 
        'Please update this form completely:');
    }
    public function process3Action ()
    {
        $registry = Zend_Registry::getInstance();
        $DB = $registry['DB'];
        $request = $this->getRequest();
        $data = array('first_name' => $request->getParam('first_name'), 
        'last_name' => $request->getParam('last_name'), 
        'user_name' => $request->getParam('user_name'), 
        'password' => md5($request->getParam('password')));
        $DB->insert('user', $data);
        $this->view->assign('title', 'Registration Process');
        $this->view->assign('description', 'Registration succes');
    }
    public function listAction ()
    {
        $registry = Zend_Registry::getInstance();
        $DB = $registry['DB'];
        $sql = "SELECT * FROM `user` ORDER BY user_name ASC";
        $result = $DB->fetchAssoc($sql);
        $this->view->assign('title', 'Member List');
        $this->view->assign('description', 'Below, our members:');
        $this->view->assign('datas', $result);
    }
    public function processeditAction ()
    {
        $registry = Zend_Registry::getInstance();
        $DB = $registry['DB'];
        $request = $this->getRequest();
        $data = array('first_name' => $request->getParam('first_name'), 
        'last_name' => $request->getParam('last_name'), 
        'user_name' => $request->getParam('user_name'), 
        'password' => md5($request->getParam('password')));
        $DB->update('user', $data, 'id = ' . $request->getParam('id'));
        $this->view->assign('title', 'Editing Process');
        $this->view->assign('description', 'Editing succes');
    }
    public function delAction ()
    {
        $registry = Zend_Registry::getInstance();
        $DB = $registry['DB'];
        $request = $this->getRequest();
        $DB->delete('user', 'id = ' . $request->getParam('id'));
        $this->view->assign('title', 'Delete Data');
        $this->view->assign('description', 'Deleting succes');
        $this->view->assign('list', $request->getBaseURL() . "/user/list");
    }
    public function statsAction ()
    {
        $ns = new Zend_Session_Namespace('HelloWorld');
        foreach ($ns as $index => $value) {
            echo "ns->$index = '$value';";
            echo "<br />";
        }
    }
    /**
	* Generate a unique random string
	*
	* @param int $length Length of string to be generated
	* @return string $str Random string
	*/
	private function generate_random_string($length=32)
	{
		// Allowable random string characters
		$seeds = 'abcdefghijklmnopqrstuvwxyz0123456789';
		
		// Generate the random string
		$str = '';
		$count = strlen($seeds);
		for ($i = 0; $length > $i; $i++)
		{
		$str .= $seeds[mt_rand(0, $count - 1)];
		}
		
		return $str;
	}	
}
?>
